﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using Sirenix.Utilities;
using UnityEditor;
using UnityToolbarExtender;

namespace Gp.Scripts.Editor
{
    public class TopToolbarDrawerAttribute : Attribute
    {
        public bool IsLeft;
        public int Order;

        public TopToolbarDrawerAttribute(bool isLeft = true, int order = 1)
        {
            IsLeft = isLeft;
            Order = order;
        }
    }

    public interface ITopToolbarDrawer
    {
        void OnToolbarGUI();
    }


    /// <summary>
    /// 绘制顶部工具栏
    /// </summary>
    [InitializeOnLoad]
    public class TopToolbarDrawer
    {
        static TopToolbarDrawer()
        {
            var types = typeof(TopToolbarDrawer).Assembly
                .GetTargetType(typeof(TopToolbarDrawerAttribute), baseClass: typeof(ITopToolbarDrawer));
            var left = types
                .Where(x => x.GetCustomAttribute<TopToolbarDrawerAttribute>().IsLeft)
                .ToArray();
            var right = types
                .Where(x => !x.GetCustomAttribute<TopToolbarDrawerAttribute>().IsLeft)
                .ToArray();
            left.Sort((a, b) =>
            {
                var aOrder = a.GetCustomAttribute<TopToolbarDrawerAttribute>().Order;
                var bOrder = b.GetCustomAttribute<TopToolbarDrawerAttribute>().Order;
                return aOrder - bOrder;
            });
            right.Sort((a, b) =>
            {
                var aOrder = a.GetCustomAttribute<TopToolbarDrawerAttribute>().Order;
                var bOrder = b.GetCustomAttribute<TopToolbarDrawerAttribute>().Order;
                return aOrder - bOrder;
            });

            left.Select(Activator.CreateInstance)
                .OfType<ITopToolbarDrawer>()
                .ForEach(x => ToolbarExtender.LeftToolbarGUI.Add(x.OnToolbarGUI));
            right.Select(Activator.CreateInstance)
                .OfType<ITopToolbarDrawer>()
                .ForEach(x => ToolbarExtender.LeftToolbarGUI.Add(x.OnToolbarGUI));
        }
    }
}